1057A - Bmail Computer Network - CodeForces Solution


*special problem dfs and similar trees *900

Please click on ads to support us..

Python Code:

n = int(input())
ll=list(map(int,input().split()))
ll.insert(0,"x")
kk=[]
i=n-1
while ll[i]!="x":
    kk.append(i+1)
    i=ll[i]-1
kk.append(1)
kk.reverse()
print(*kk)

C++ Code:

#include <iostream>
#include <algorithm>
using namespace std;

const int mn = 2e5 + 10;
int p[mn];
int sol[mn];

int main()
{
    // numero de enrutadores (o nodos)
    int n;
    scanf("%d", &n);

    // p_i es igual al indice del enrutador al que se conecto el i-esimo enrutador
    // despues de comprarlo
    // el primer enrutador va a tener p_i = 0
    p[0] = 0;
    for (int i = 1; i < n; i++)
    {
        cin >> p[i];
        p[i]--;
    }

    int k = n - 1, cnt = 0;
    // recorremos el grafo desde el nodo n -1 hacia arriba, hasta llegar a la raiz
    while (p[k] != k)
    {
        sol[cnt++] = k;
        // ponemos k igual a p_k
        k = p[k];
    }
    sol[cnt++] = 0;

    // ahora, imprimimos el arreglo sol en orden reverso
    reverse(sol, sol + cnt);
    for (int i = 0; i < cnt; i++)
    {
        printf("%d ", sol[i] + 1);
    }
    printf("\n");

    return 0;
}


Comments

Submit
0 Comments
More Questions

479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK